<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>My Column Chart</title>
    <script type="text/javascript" src="../lib/d3v4.js"></script>

</head>
<body>
<style>
    .MyRect {
        fill: steelblue;
    }

    .MyText {
        fill: white;
        text-anchor: middle;  /* 位置(x,y)处于文本的位置*/
        font-size:20px;
    }

    .axis path,
    .axis line {
        fill: none;
        stroke: black;
        shape-rendering: crispEdges;
    }

    .axis text {
        font-family: sans-serif;
        font-size: 11px;
    }
</style>

<script>
    var width = 500, height = 600;
    var svg = d3.select("body")
        .append("svg")
        .attr("width", width)
        .attr("height", height)
        .attr("transform", "translate(0,0)");

    var data = [24, 42, 66, 42];

    var padding = {left: 30, right: 30, top: 20, bottom: 20};


    var xScale = d3.scaleBand()
        .domain(d3.range(data.length))
        .rangeRound([0, width - padding.left - padding.right])
        .padding(0.1);

    var yScale = d3.scaleLinear()
        .domain([0, d3.max(data)])
        .range([height - padding.top - padding.bottom, 0]);

    var xAxis = d3.axisBottom().scale(xScale);

    var yAxis = d3.axisLeft().scale(yScale);

    var rects = svg.selectAll(".MyRect")
        .data(data)
        .enter()
        .append("rect")
        .attr("transform", "translate(" + padding.left + "," + padding.top + ")")
        .attr("class", "MyRect")
        .attr("x", function (d, i) {
            return xScale(i);      //Warning!
        })
        .attr("y", function (d) {
            return yScale(d);
        })
        .attr("width", xScale.bandwidth())
        .attr("height", function (d) {
            return height - padding.top - padding.bottom - yScale(d);
        });


    var text = svg.selectAll(".MyText")
        .data(data)
        .enter()
        .append("text")
        .attr("class", "MyText")
        .attr("transform", "translate(" + padding.left + "," + padding.top + ")")
        .attr("x", function (d, i) {
            return xScale(i)
        })
        .attr("y", function (d) {
            return yScale(d);
        })
        .attr("dx", function () {
            return xScale.bandwidth()/2 ;
        })
        .attr("dy", function (d) {
            return 40;
        })
        .text(function (d) {
            return d;
        });

    svg.append("g")
        .attr("class", "axis")
        .attr("transform", "translate(" + padding.left + "," + (height - padding.bottom) + ")")
        .call(xAxis);

    //添加y轴
    svg.append("g")
        .attr("class", "axis")
        .attr("transform", "translate(" + padding.left + "," + padding.top + ")")
        .call(yAxis);

</script>

</body>
</html>